/*
 * MIT License
 *
 * Copyright (c) 2023 北京凯特伟业科技有限公司
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
package com.je.rbac.rpc.workflow.user;

import com.google.common.base.Strings;
import com.je.common.base.DynaBean;
import com.je.common.base.service.MetaService;
import com.je.common.base.spring.SpringContextHolder;
import com.je.core.entity.extjs.JSONTreeNode;
import com.je.ibatis.extension.conditions.ConditionsWrapper;
import com.je.rbac.rpc.workflow.user.special.SpecialUserParserEnum;
import com.je.rbac.rpc.workflow.user.special.SpecialUserParserFactory;

import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import static com.ibm.icu.impl.locale.KeyTypeData.ValueType.multiple;

/**
 * 公司、人员树
 */
public class ParserCompanyUserJsonTreeFilter extends FilterChain implements Filter {

    @Override
    public void handler(ParserUserBo parserUserBo, JSONTreeNode jsonTreeNode , FilterChain filterChain) {
        List<String> types = parserUserBo.getTypes();
        //选择类型不为空
        if (types != null && types.size() > 0) {
            //包含本公司监管领导 、或者本公司领导 则渲染公司、人员树
            if (!types.contains(SpecialUserParserEnum.COMPANY_MONITOR_LEADERS.toString())
                    && !types.contains(SpecialUserParserEnum.COMPANY_LEADERS.toString())) {
                filterChain.doFilter(parserUserBo, jsonTreeNode, filterChain);
                return;
            }
            //获取本公司领导的唯一信息
            List<DynaBean> leadersUserInfos = SpecialUserParserFactory.getParserByCode(SpecialUserParserEnum.COMPANY_LEADERS.toString()).getUserInfo(parserUserBo.getUserId(), parserUserBo.getAddOwn());

            //获取公司监管领导的唯一信息
            List<DynaBean> monitorUserInfos = SpecialUserParserFactory.getParserByCode(SpecialUserParserEnum.COMPANY_MONITOR_LEADERS.toString()).getUserInfo(parserUserBo.getUserId(), parserUserBo.getAddOwn());
            //去重
            List<DynaBean> userInfos = new ArrayList<>();
            if (leadersUserInfos != null && monitorUserInfos != null) {
                userInfos = Stream.of(leadersUserInfos, monitorUserInfos)
                        .flatMap(Collection::stream)
                        .distinct()
                        .collect(Collectors.toList());
            }
            if (leadersUserInfos != null && monitorUserInfos == null) {
                userInfos = leadersUserInfos;
            }
            if (leadersUserInfos == null && monitorUserInfos != null) {
                userInfos = monitorUserInfos;
            }

            //已经有了公司部门人员树，看所选本公司领导、或者监管领导在不在公司树上，如果不在新建公司树
            if (parserUserBo.getCompanyDeptUserTree()) {

                //获取账号部门id
                List<String> idList = userInfos.stream().map(bean -> bean.getStr("JE_RBAC_ACCOUNTDEPT_ID")).collect(Collectors.toList());
                //检查树上有没有的人员id
                List<String> accountDeptIds = new ArrayList<>();
                for (String userId : idList) {
                    if (JsonTreeContext.getJsonTree(userId) == null) {
                        accountDeptIds.add(userId);
                    }
                }

                if (accountDeptIds.size() > 0) {
                    //未构建树的人员信息
                    List<DynaBean> dynaBeanList = userInfos.stream().filter(bean -> accountDeptIds.contains(bean.getStr("JE_RBAC_ACCOUNTDEPT_ID")))
                            .collect(Collectors.toList());

                    //构建公司人员树
                    buildCompanyUserTree(dynaBeanList, parserUserBo);

                }
            } else {
                //如果没有公司部门人员树，只构建公司人员树
                buildCompanyUserTree(userInfos, parserUserBo);
                //此时的jsonTreeNode是公司人员树
                parserUserBo.setCompanyUserTree(true);
            }
            //去除重复选项
            removeOtherOption(parserUserBo, jsonTreeNode);
            filterChain.doFilter(parserUserBo, jsonTreeNode, filterChain);
        }
    }

    private void removeOtherOption(ParserUserBo parserUserBo, JSONTreeNode jsonTreeNode) {
        //本公司监管领导
        parserUserBo.getTypes().remove(SpecialUserParserEnum.COMPANY_MONITOR_LEADERS.toString());
        //本公司领导
        parserUserBo.getTypes().remove(SpecialUserParserEnum.COMPANY_LEADERS.toString());

    }

    private void buildCompanyUserTree(List<DynaBean> dynaBeanList, ParserUserBo parserUserBo) {
        //根据部门id分组
        Map<String, List<DynaBean>> deptListMap = dynaBeanList.stream().collect(Collectors.groupingBy(bean -> bean.getStr("ACCOUNTDEPT_DEPT_ID")));

        //查找部门所属公司，在不在树上，并构建公司部门人员信息
        checkCompany(deptListMap, parserUserBo.getMultiple());

    }
}
